/**
 * 
 */
package org.vsg.security.model.presentation.spring;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.vsg.common.pagination.Pagination;
import org.vsg.common.pagination.apps.HttpApplicationContext;
import org.vsg.common.pagination.apps.HttpPaginationApplicationContextFactory;
import org.vsg.common.pagination.apps.PaginationApplicationContext;
import org.vsg.common.pagination.apps.RecordLimitCarrierApplicationContext;
import org.vsg.common.pagination.carrier.HttpSingleSortRecordLimitCarrier;
import org.vsg.common.pagination.carrier.RecordLimitCarrier;
import org.vsg.common.web.json.ListResult;
import org.vsg.common.web.json.LoadRecordResult;
import org.vsg.common.web.json.SubmitResult;
import org.vsg.common.web.json.processor.JsTimestampJsonValueProcessor;
import org.vsg.security.model.domain.SysRole;
import org.vsg.security.model.domain.SysUser;
import org.vsg.security.model.service.SysRoleService;
import org.vsg.security.model.service.SysUserService;
import org.vsg.security.model.vo.json.SysRoleConflictVO;
import org.vsg.security.model.vo.json.SysRoleListVO;
import org.vsg.security.model.vo.json.SysUserSimpleFormVO;
import org.vsg.security.model.vo.json.UserVO;

/**
 * @author Bill Vison
 *
 */
@Controller
public class UserController {

	private final static Logger logger = LoggerFactory.getLogger(UserController.class);	
	
	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysRoleService sysRoleService;
	

	@RequestMapping("/pageUser.do")
	public String pageUser(HttpServletRequest request , HttpServletResponse res) throws Exception {

		
		// generate pagination application and set the request
		PaginationApplicationContext pageAppsContext = HttpPaginationApplicationContextFactory.getPaginationContext(request);
		// set parameter passed in pagination url
		RecordLimitCarrierApplicationContext recordLimitAppsContenxt = (RecordLimitCarrierApplicationContext)pageAppsContext;
		
		HttpApplicationContext httpContext = (HttpApplicationContext)pageAppsContext;

		httpContext.addParameterName("name");
		httpContext.addParameterName("code");
		httpContext.addParameterName("flagInactive");		

		
		// set the data to attribute
		RecordLimitCarrier limitCarrier = recordLimitAppsContenxt.generateRecordLimitCarrier( HttpSingleSortRecordLimitCarrier.class );
		
		Pagination page = sysUserService.pageSysUser(limitCarrier );
		
		request.setAttribute("pagination", page);
	
		request.setAttribute("currentUri",request.getRequestURI());
		
		// --- list defined ---
		List<UserVO> listObj = new Vector<UserVO>();
		
		Collection<SysUser> userList = page.getPaginationList();
		for (SysUser user : userList) {
			listObj.add( new UserVO(user) );
		}
		
		// --- parse the json ---
		ListResult lr = new ListResult();
		lr.setResults( page.getTotalRecord() );
		lr.setRows( listObj );
		
		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());
		JSONObject jsonObject = JSONObject.fromObject(lr ,jcfg ); 
		
		request.setAttribute("json", jsonObject);
		
		// --- use log show
		logger.info(jsonObject.toString());			
		
		return "json";
	}
	
	@RequestMapping("/addUser.do")
	public String addUser(HttpServletRequest req , HttpServletResponse res , SysUser sysUser) throws Exception {
		Calendar cale = Calendar.getInstance();

		sysUser.setCreatedDate( new Timestamp(cale.getTimeInMillis()) );
		
		// insert user
		sysUserService.addSysUser( sysUser );

		
	
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setMsg( "新增成功!" );
		
		JSONObject jsonObject = JSONObject.fromObject(submitResult ); 
		
		req.setAttribute("json", jsonObject);
		
		return "result";
	}
	
	@RequestMapping("/updateUser.do")
	public String updateRole(HttpServletRequest req , HttpServletResponse res , SysUser sysUser) throws Exception {
		
		sysUserService.updateSimpleSysUser(sysUser);
		
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setMsg( "修改成功!" );		
		JSONObject jsonObject = JSONObject.fromObject(submitResult ); 
		
		req.setAttribute("json", jsonObject);		
		
		return "result";
	}
	
	@RequestMapping("/loadUser.do")
	public String loadRole(HttpServletRequest req , HttpServletResponse res , int userId) throws Exception {

		SysUser sysUser = this.sysUserService.loadSysUser( userId );
		
		// --- json result object ---
		LoadRecordResult recordResult = new LoadRecordResult();
		recordResult.setSuccess(true);
		recordResult.setData( new SysUserSimpleFormVO(sysUser) );

		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());

		JSONObject jsonObject = JSONObject.fromObject( recordResult  , jcfg); 
		
		logger.debug( jsonObject.toString() );
	
		req.setAttribute("json", jsonObject);		
		
		return "result";
	}
	
	@RequestMapping("/removeUsers.do")
	public String removeUsers(HttpServletRequest req , HttpServletResponse res , int[] userId) throws Exception {
		

		this.sysUserService.removeUsers(userId);
		
	
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setMsg( "移除用户数据成功" );

		JSONObject jsonObject = JSONObject.fromObject(submitResult ); 
		
		req.setAttribute("json", jsonObject);
		
		// --- use log show
		logger.info(jsonObject.toString());	
		
		
		return "result";
	}
	
	@RequestMapping("/assignRolesOfUser.do")
	public String assignRolesOfUser(HttpServletRequest req ,  int userId) throws Exception {
		
		SysUser sysUser = this.sysUserService.loadSysUser( userId );
		
		Set<SysRole> assignedRoles = sysUser.getAssignedRoles();

		Collection<SysRoleConflictVO> tmpRoleVoList = new Vector<SysRoleConflictVO>();
		for (SysRole role : assignedRoles) {
			tmpRoleVoList.add(new SysRoleConflictVO(role));
		}

		
		// --- json result object ---
		ListResult lr = new ListResult();
		lr.setResults( tmpRoleVoList.size() );
		lr.setRows( tmpRoleVoList );

		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());

		JSONObject jsonObject = JSONObject.fromObject( lr  , jcfg); 
		
		logger.info( jsonObject.toString() );
	
		req.setAttribute("json", jsonObject);
		
		return "json";
	}
	
	@RequestMapping("/pageAvailableRolesOfUser.do")
	public String pageAvailableRolesOfUser(HttpServletRequest req ) throws Exception {
		
		// generate pagination application and set the request
		PaginationApplicationContext pageAppsContext = HttpPaginationApplicationContextFactory.getPaginationContext(req);
		// set parameter passed in pagination url
		RecordLimitCarrierApplicationContext recordLimitAppsContenxt = (RecordLimitCarrierApplicationContext)pageAppsContext;
		
		HttpApplicationContext httpContext = (HttpApplicationContext)pageAppsContext;
		
		httpContext.addParameterName("userId");
		
		// set the data to attribute
		RecordLimitCarrier limitCarrier = recordLimitAppsContenxt.generateRecordLimitCarrier( HttpSingleSortRecordLimitCarrier.class );
		
		Pagination page = sysRoleService.pageAvailableRolesOfUser(limitCarrier);
		
		Collection<SysRole> sysRoleList = page.getPaginationList();
		
		Collection<SysRoleListVO> tmpRoleVoList = new Vector<SysRoleListVO>();
		for (SysRole role : sysRoleList) {
			tmpRoleVoList.add(new SysRoleListVO(role));
		}
		
		// --- parse the json ---
		ListResult lr = new ListResult();
		lr.setResults( page.getTotalRecord() );
		lr.setRows( tmpRoleVoList );
		
		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());
		JSONObject jsonObject = JSONObject.fromObject(lr ,jcfg ); 
		
		// --- set attribute ---
		req.setAttribute("json", jsonObject);		
		return "json";
	}

	@RequestMapping("/addUserAssignedRole.do")
	public String addUserAssignedRole(HttpServletRequest req , SysUser user , String[] roleIds) throws Exception {
		
		sysUserService.assignRolesToUser(user, roleIds);
		
		
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setMsg( "分配角色成功!" );		
		JSONObject jsonObject = JSONObject.fromObject(submitResult ); 
		
		req.setAttribute("json", jsonObject);		
		
		return "result";
	}

	@RequestMapping("/removeUserAssignedRole.do")
	public String  removeUserAssignedRole(HttpServletRequest req , SysUser user , String[] roleIds) throws Exception {
		
		sysUserService.removeUserAssignedRole(user, roleIds);
		
	
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setMsg( "移除角色成功!" );		
		JSONObject jsonObject = JSONObject.fromObject(submitResult ); 
		
		req.setAttribute("json", jsonObject);
		
		return "result";
	}
	
	
	
}
